package com.itheima.service.impl;

import com.itheima.dao.IUserInfoDao;
import com.itheima.domain.Role;
import com.itheima.domain.UserInfo;
import com.itheima.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 登录业务类
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserInfoDao userInfoDao;

    /**
     * 登录校验
     *
     * @param username 登录页面传递过来的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = null;
        User user = null;
        try {
            userInfo = userInfoDao.findByUserInfoUsername(username);
            //将对userinfo对象转为UserDetails并获得权限
            user = new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getStatus() == 0 ? false : true,
                    true, true, true, getAuthority(userInfo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }


    /**
     * 获得用户权限
     *
     * @param userInfo
     * @return
     */
    public List<SimpleGrantedAuthority> getAuthority(UserInfo userInfo) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        //遍历角色
        for (Role role : userInfo.getRoles()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        return authorities;
    }
}
